class Solution
{
public:
    long long countGood(vector<int> &nums, int k)
    {
        long long result = 0;
        int n = nums.size();
        int front = 0;
        int back = 0;
        unordered_map<int, int> numCount;
        numCount[nums[front]] = 1;
        int goodPairCount = 0;
        while (back < n - 1)
        {
            if (front == back || goodPairCount < k)
            {
                ++back;
                goodPairCount += numCount[nums[back]];
                ++numCount[nums[back]];
            }
            if (goodPairCount >= k)
            {
                result += n - back;
                goodPairCount -= numCount[nums[front]] - 1;
                --numCount[nums[front]];
                ++front;
            }
        }
        while (front < n - 1)
        {
            if (goodPairCount >= k)
            {
                result += 1;
                goodPairCount -= numCount[nums[front]] - 1;
                --numCount[nums[front]];
                ++front;
            }
            else
            {
                break;
            }
        }
        return result;
    }
};